const Stock = require("./modules/Stock")
const $request = require("./utils/request")
const $asyncForeach = require("./utils/asyncForeach")

const { host } = require(`./env`)

const scan = async () => {
    /**
    * 获取服务器需要获取的个股信息
    */
    let { data: list } = await $request({ url: `${host}/stock/quantitativeTrading/getScanStockList` })

    /**
     * 筛选逻辑
     */
    let allSettled = await $asyncForeach({
        list, fn: async ({ code, name }, index) => {

            let result = null

            let stock = new Stock({ code, type: "stock", options: { name, market_type: "ab" } })
            let transaction = await stock.getTransaction({ ktype: "day" })

            let details = await stock.generateDetails({ transaction })

            /** 找出离 ma5 <= 5个点的个股 */
            let latestMaDifference = Stock.latestMaDifference({ details })
            if (latestMaDifference.percentage <= -5) {
                result = { code, name, percentage: latestMaDifference.percentage }
            }

            console.log({ code, name, percentage: latestMaDifference.percentage })

            return result
        }
    })

    /**
     * 将符合的条件提交到服务器
     */
    let stockList = allSettled.filter(item => item)

    if (stockList.length) {
        await $request({
            url: `${host}/stock/quantitativeTrading/updateStockList`,
            method: "POST",
            data: {
                stockList
            }
        })
    }
}

scan()


